package com.diandi.messages.service.impl.phone;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.diandi.messages.bean.freeSign.MsgFreeSign;
import com.diandi.messages.bean.phone.MessageMsg;
import com.diandi.messages.bean.template.MsgPassTemplate;
import com.diandi.messages.enums.MessageMsgPassEnums;
import com.diandi.messages.enums.MessagesMsgEnums;
import com.diandi.messages.enums.ReturnCode;
import com.diandi.messages.manager.freeSign.MsgFreeSignManager;
import com.diandi.messages.manager.phone.MessageMsgManager;
import com.diandi.messages.manager.phone.MessageMsgPassManager;
import com.diandi.messages.manager.template.MsgPassTemplateManager;
import com.diandi.messages.properties.MessagePlatformProperties;
import com.diandi.messages.service.phone.MessageMsgService;
import com.diandi.messages.tools.CreateTradeNo;
import com.diandi.messages.tools.Tools;
import com.diandi.messages.util.AliBigFishUtil;
import com.diandi.messages.util.AliSMSDto;
import com.diandi.messages.utils.http.CheckParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author mwz
* @create 2017-09-15 16:12
* @version V1.0.0
* @description description
*/
@Service
public class MessageMsgServiceImpl implements MessageMsgService {

    private static Logger logger = LoggerFactory.getLogger( MessageMsgServiceImpl.class );

    @Autowired
    MessageMsgManager messageMsgManager;

    @Autowired
    MessageMsgPassManager messageMsgPassManager;

    @Autowired
    MessagePlatformProperties messagePlatformProperties;

    @Autowired
    private MsgPassTemplateManager msgPassTemplateManager;

    @Autowired
    private MsgFreeSignManager msgFreeSignManager;

    @Override
    public MessageMsg getMessageMsg(Map<String, String> paramMap) {
        return messageMsgManager.getMessageMsg( paramMap );
    }



    @Override
    public Map<String, String> sendMessages(HttpServletRequest request, String platTradeNo) {

        /**
         * 1.1 验证业务端签名信息的正确性
         */
        logger.info("--platTradeNo:"+platTradeNo+":[消息平台]: 开始业务平台验签");
        Map<String, String> returnMap = new HashMap<String, String>();
        try{
             Map<String, String> params = Tools.checkBusinessSign(request,  messagePlatformProperties, "platfrom");
//            Map<String, String> params = Tools.getParameterMap(request, false);
            if (params.containsKey("error")) {
                logger.info("--rcv:platTradeNo:"+platTradeNo+":[消息平台]: 业务平台验签失败--");
                returnMap = Tools.createReturnParams(ReturnCode.err_9001, ReturnCode.err_9001.getMsg(), params.get("error"));
                return returnMap;
            }
            logger.info("--platTradeNo:"+platTradeNo+":[消息平台]: 业务平台验签成功--");

            returnMap = CheckParams.checkParamsIsExist(params, "merchantNo", "msgList" );
            if (returnMap != null && !returnMap.isEmpty()){
                logger.info("--rcv:platTradeNo:" + platTradeNo + ":[消息平台],校验参数为空:" + returnMap.toString() +"--");
                return returnMap;
            }

            /**
             * 依据渠道来选择性的发送消息
             */

            MsgPassTemplate msgPassTemplate = msgPassTemplateManager.querySingle(params.get("merchantNo"), params.get("msgTemplateCode"), 1);

            if( msgPassTemplate == null ){
                returnMap = Tools.createReturnParams(ReturnCode.err_8001, ReturnCode.err_8001.getMsg(),"");
                return returnMap;
            }

            /*if (!msgPassTemplate.getFreeSignId().equals(params.get("freeSignId"))){
                returnMap = Tools.createReturnParams(ReturnCode.err_8001, ReturnCode.err_8001.getMsg(),"");
                return returnMap;
            }*/

            //查询模板签名
            MsgFreeSign msgFreeSign = msgFreeSignManager.querySingle(msgPassTemplate.getFreeSignId(), 1);
            if (msgFreeSign == null){
                returnMap = Tools.createReturnParams(ReturnCode.err_8001, ReturnCode.err_8001.getMsg(),"");
                return returnMap;
            }

            params.put("freeSignName", msgFreeSign.getFreeSignText());
            params.put("templateCode", msgPassTemplate.getPassTemplateCode());

            if( msgPassTemplate.getPassCode().equals( MessageMsgPassEnums.短信通道_阿里大于.getValue() )){
                returnMap = SendToPass01Msg( platTradeNo,params );
            }else {
                returnMap = Tools.createReturnParams(ReturnCode.err_8002, ReturnCode.err_8002.getMsg(),"");
                return returnMap;
            }


            return returnMap;
        }catch ( Exception e ){
            e.printStackTrace();
            returnMap = Tools.createReturnParams(ReturnCode.err_8001, ReturnCode.err_8001.getMsg(),"");
            return returnMap;
        }

    }

    public Map<String,String> SendToPass01Msg( String platTradeNo,  Map<String, String> params){
        Map<String, String> returnMap = new HashMap<String, String>();
        JSONObject jsonObject = JSONObject.parseObject( params.get("msgList") );
        List<Map<String, String>> msgList = new ArrayList<Map<String, String>>();
        JSONArray msgListArray = JSONArray.parseArray( jsonObject.getString("msgList") );
        Map<String, String> msgListMap = null;
        for (Object msgInfo : msgListArray) {
            msgListMap = (Map<String, String>) msgInfo;
            msgList.add(msgListMap);
        }

        /**
         * 2.1 记录中间状态、及数据信息表
         */
        Map<String,String> rtnMap = new HashMap<String, String>();
        for( Map<String,String> mapInfo : msgList ){
            String messageTrade = CreateTradeNo.createTradeNo("BC");
            Map<String,String> queryMap = new HashMap<String,String>();

            String userId = "";
            if (mapInfo.get("userId") != null){
                userId = mapInfo.get("userId");
            }

            queryMap.put("messageTrade", messageTrade );
            queryMap.put("messageBatchTrade",platTradeNo);
            queryMap.put("passCode",params.get("passCode"));
            queryMap.put("businessId",mapInfo.get("businessId"));
            queryMap.put("merchantNo",params.get("merchantNo"));
            queryMap.put("userId", userId);
            queryMap.put("msgTemplateCode",params.get("msgTemplateCode"));
            queryMap.put("phoneId",mapInfo.get("phone"));


            /**
             * 记录数据库
             */
            messageMsgManager.saveMessageData( queryMap );
            logger.info("--platTradeNo:"+platTradeNo+":[消息平台]: 记录数据库完成--");

//            JSONObject jsonParamObject = JSONObject.parseObject(mapInfo.toString() );


            Map<String,Object> msgMap = new HashMap<String, Object>();
            msgMap = JSONObject.parseObject(JSONObject.toJSONString(mapInfo.get("paramList")));


            /*if (StringUtils.isNotBlank(jsonParamObject.getString("paramList"))){
                JSONArray paramListArray = JSONArray.parseArray( jsonParamObject.getString("paramList") );
                for ( Object parmInfo : paramListArray ){
                    Map<String, String> map = (Map<String, String>) parmInfo;
                    for ( String in : map.keySet()) {
                        String str = map.get(in);
                        msgMap.put(in,str);
                    }
                }
            }*/

            logger.info("--platTradeNo:"+platTradeNo+":[消息平台]: 组织发送内容"+msgMap.toString()+"完成--");
            AliSMSDto aliSMSDto = new AliSMSDto();

            aliSMSDto.setMobilePhone( mapInfo.get("phone") );
            aliSMSDto.setSmsFreeSignName(params.get("freeSignName"));
            if (!msgMap.isEmpty()){
                aliSMSDto.setSmsParam(msgMap);
            }
            aliSMSDto.setUserId(userId);
            aliSMSDto.setTemplateCode(params.get("templateCode") );
            rtnMap = AliBigFishUtil.sendMsg(aliSMSDto);
            logger.info("--platTradeNo:"+platTradeNo+":[消息平台]: 发送短信完成,状态："+rtnMap.toString()+"--");
            /**
             * 4.1 更新中间状态及数据表信息
             */
            if( !rtnMap.isEmpty()){
                returnMap.put("messageTrade",messageTrade);
                returnMap.put("returnMsg",rtnMap.toString());
                returnMap.put("code", "0");
                returnMap.put("msg", "success");
            }

            messageMsgManager.updateMessageData( returnMap,   MessagesMsgEnums.处理成功.getNumber() );
            logger.info("--platTradeNo:"+platTradeNo+":[消息平台]: 更新数据库完成--");
        }
        return returnMap;
    }
}
